#include <jni.h>
#include "config.h"
#include "ilog.h"
#include <string.h>

//jstring to char*
char* jstringTostring(JNIEnv* env, jstring jstr) {
	LOG_W("jstringTostring");
	char* rtn = NULL;
	jclass clsstring = (*env)->FindClass(env, "java/lang/String");
	LOG_W("FindClass");
	jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes",
			"(Ljava/lang/String;)[B");
	LOG_W("GetMethodID");
	jstring strencode = (*env)->NewStringUTF(env, "ASCII");
	jarray barr = (*env)->CallObjectMethod(env, jstr, mid, strencode);
	LOG_W("CallObjectMethod");
	jsize alen = (*env)->GetArrayLength(env, barr);
	LOG_W("alen : %d ", alen);
	jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);
	if (alen > 0) {
		rtn = (char*) malloc(alen + 1);
		memcpy(rtn, ba, alen);
		rtn[alen] = 0;
	}
	(*env)->ReleaseByteArrayElements(env, barr, ba, 0);
	return rtn;
}
//char* to jstring
jstring stoJstring(JNIEnv* env, const char* pat) {
	jclass strClass = (*env)->FindClass(env, "java/lang/String");
	jmethodID ctorID = (*env)->GetMethodID(env, strClass, "<init>",
			"([BLjava/lang/String;)V");
	jarray bytes = (*env)->NewByteArray(env, strlen(pat));
	(*env)->SetByteArrayRegion(env, bytes, 0, strlen(pat), (jbyte*) pat);
	jstring strencode = (*env)->NewStringUTF(env, "utf-8");
	return (*env)->NewObject(env, strClass, ctorID, bytes, strencode);
}

void Java_com_ransj_iphone_Iservice_init(JNIEnv *env, jobject obj,
		jobject context) {
	jclass cls_context = (*env)->GetObjectClass(env, context);
	jmethodID code_path = (*env)->GetMethodID(env, cls_context,
			"getPackageCodePath", "()Ljava/lang/String;");
	LOG_W("ERROR GET METHOD");
	jstring str_path = (*env)->CallObjectMethod(env, context, code_path);
	LOG_W("str_path : %d", (*env)->GetStringLength(env, str_path));
	char* char_path = jstringTostring(env, str_path);
	LOG_W("char_path : %s ", char_path);
	const char* command_1 = "export CLASSPATH=";
	const char* command_2 =
			"\nexec app_process /system/bin com.ransj.iphone.utils.Input $*\n";
	int length = strlen(command_1) + strlen(command_2) + strlen(char_path);
	char* result = (char*) malloc(length);
	strcpy(result, command_1);
	LOG_W("char_path1 : %s ", result);
	strcat(result, char_path);
	LOG_W("char_path2 : %s ", result);
	strcat(result, command_2);
	LOG_W("char_path3 : %s ", result);
	jstring str_result = stoJstring(env, result);
	jstring str_name = (*env)->NewStringUTF(env, "iphone");
	jclass cls_utils = (*env)->FindClass(env, "com/ransj/iphone/utils/IUtils");
	jmethodID file_write = (*env)->GetStaticMethodID(env, cls_utils,
			"writeFile",
			"(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V");
	(*env)->CallStaticVoidMethod(env, cls_utils,file_write,  context, str_name, str_result);
}
